﻿using System;
using Microsoft.SharePoint.Administration;
using SharePointOfView.SPReporting.Jobs;
using System.Reflection;

namespace SharePointOfView.SPReporting
{
    public sealed class JobUtilities
    {
        /// <summary>
        /// Clean up job occurences
        /// </summary>
        /// <param name="jobName">Job's name to delete</param>
        public static void CleanUpJob(string jobName)
        {
            // Make sure the job isn't already registered.
            SPService spTimerService = SPFarm.Local.Services.GetValue<SPTimerService>(Globals.SPTimerServiceName);
            foreach (SPJobDefinition job in spTimerService.JobDefinitions)
            {
                if (job.Name == jobName)
                    job.Delete();
            }
        }

        /// <summary>
        /// Run a job
        /// </summary>
        /// <param name="jobId">Job's Unique Identifier</param>
        /// <returns></returns>
        public static bool RunJob(Guid jobId)
        {
            // Make sure the job isn't already registered.
            SPService spTimerService = SPFarm.Local.Services.GetValue<SPTimerService>(Globals.SPTimerServiceName);
            SPJobDefinition job = spTimerService.JobDefinitions[jobId];
            if (job != null)
            {
                job.Execute(Guid.Empty);
                return true;
            }
            return false;
        }
    }
}